package com.toppitch.site.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.toppitch.site.data.HedgeFund;
import com.toppitch.site.data.JsonData;
import com.toppitch.site.data.Student;
import com.toppitch.site.db.DBManager;
import com.toppitch.site.mail.MailUtils;

@Controller
@RequestMapping("/")
public class ForgetPasswordController {
	@Autowired
	private DBManager dbmanager;
	@Autowired
	private MailUtils mailUtils;
	
	@RequestMapping("forgetPassword")
	public String forgetPassword(//
			@RequestParam("email") String email,//
			@RequestParam(value = "userType", defaultValue = "student") String userType,//
			ModelMap modelMap) {
		JsonData json = new JsonData();
		modelMap.addAttribute("jsonData", json);
		String emailResult = null;
		String passwordResult = null;
		if (userType.equalsIgnoreCase("student")) {
			Student student = new Student();
			dbmanager.queryFirst(student, "select * from student where lower(email)=?", email.toLowerCase());
			emailResult = student.getEmail();
			passwordResult = student.getPassword();
		} else {
			HedgeFund hf = new HedgeFund();
			dbmanager.queryFirst(hf, "select * from hf where lower(email)=?", email.toLowerCase());
			emailResult = hf.getEmail();
			passwordResult = hf.getPassword();
		}
		if (email.equalsIgnoreCase(emailResult)) {
			mailUtils.sendGmail(email, "Your password at Top Pitch!", "<html><head></head><body><strong>" + passwordResult + "</strong></body></html>");
			json.setSucceed(true);
		} else {
			json.setSucceed(false);
			json.setErrorMessage("User " + email + " does not exist.");
		}
		return "json";
	}
}
